/*
 *  Copyright 2010 mazhao.
 * 
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 * 
 *       http://www.apache.org/licenses/LICENSE-2.0
 * 
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *  under the License.
 */

package shopping.management;

import com.opensymphony.xwork2.ModelDriven;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Result;

import shopping.commons.BaseAction;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import shopping.model.Catalog;
import shopping.model.Product;


/**
 *
 * @author mazhao
 */
public class ProductAction extends BaseAction implements ModelDriven<Product> {
    
    private Log log = LogFactory.getLog(this.getClass());

    private Product product = new Product();
    private List<Product> productList = new ArrayList<Product>();

    // ---- begin for catalog search ----
    private int currentCatalogId = 0;
    private List<Catalog> catalogPath = new ArrayList<Catalog>();
    private List<Catalog> subCatalog = new ArrayList<Catalog>();
    // ---- end   for catalog search ----
    
    
    //-------------------------------------------------
    // action end
    //-------------------------------------------------
    
    @Action(value = "/management/productlist",
        results={
            @Result(name="success", location="/WEB-INF/content/management/product.jsp")
        }
    )
    public String list() {
        log.debug("enter product list method");

        // get current catalog id
        if(currentCatalogId == 0) {
            log.debug("set catalog id to default");
            currentCatalogId = ManagementConstants.CATALOG_ROOT_ID;
        }

        // get catalog path
        Catalog curCatalog = new Catalog();
        curCatalog.setId(currentCatalogId);

        // select path to current catalog
        catalogPath = curCatalog.pathToMe( );
        if(log.isDebugEnabled()) {
            StringBuilder sb = new StringBuilder("  ");
            for(Catalog c : catalogPath) {
                log.debug("catalog path:" + sb.toString() + c);
                sb.append("  ");
            }
        }

        // select sub catalogs of current catalog
        subCatalog = curCatalog.subCatalogs();
        if(log.isDebugEnabled()) {
            for(Catalog c : subCatalog) {
                log.debug("sub catalog:" + c);
            }
        }

        // list product use current catalog id
        productList = Product.getAllProductsOfCatalog(currentCatalogId);
        if(log.isDebugEnabled()) {
            log.debug("find some product:" + productList.size());
            for(Product p : productList) {
                log.debug(p);
            }
        }

        return SUCCESS;
    }

    @Action (
        value ="/management/productcreate" ,
        results = {
            @Result( name = "success", location="/management/productlist", type="redirect" , params={"currentCatalogId", "${currentCatalogId}"})
        }
    )
    public String insert() {
        log.debug("enter product create, create:" + getModel());
        
        currentCatalogId = getModel().getCatalogId();

        getModel().save();

        return SUCCESS;
    }

    @Action(
        value = "/management/productupdate",
        results = {
            @Result(name="success", location="/management/productlist", type="redirect", params={"currentCatalogId", "${currentCatalogId}"})
        }
    )
    public String update() {
        if(log.isDebugEnabled()) {
            log.debug("update model:" + getModel() );
        }

        // set the current catalog for product list redirect
        currentCatalogId = getModel().getCatalogId();

        getModel().update();

        return SUCCESS;
    }

    @Action(
        value="/management/productdelete",
        results ={
            @Result(name="success", location ="/management/productlist", type="redirect", params={"currentCatalogId", "${currentCatalogId}"})
        }
    )
    public String delete() {

        currentCatalogId = getModel().getCatalogId();
        
        Product p = getModel();
        p.delete();

    	return SUCCESS;
    }

    // ----------------------------------
    // for image upload begin
    // ----------------------------------
    private File image;
    private String imageFileName;
    private String imagContentType;
    private int currentProductId;

    public static final String KEY_PRODUCT_IMAGE_DIR = "product.uploaddir";

    public String getImagContentType() {
        return imagContentType;
    }

    public void setImagContentType(String imagContentType) {
        this.imagContentType = imagContentType;
    }

    public String getImageFileName() {
        return imageFileName;
    }

    public void setImageFileName(String imageFileName) {
        this.imageFileName = imageFileName;
    }

    
    public int getCurrentProductId() {
        return currentProductId;
    }

    public void setCurrentProductId(int currentProductId) {
        this.currentProductId = currentProductId;
    }

    
    public File getImage() {
        return image;
    }

    public void setImage(File image) {
        this.image = image;
    }

    
    @Action(
        value="/management/productupload",
        results ={
            @Result(name="success", location ="/management/productlist", type="redirect", params={"currentCatalogId", "${currentCatalogId}"})
        }
    )
    public String upload() {
        if(log.isDebugEnabled()) {
            log.debug("enter management product upload action");
            log.debug("file:" + image);
            log.debug("currentProductId:" + currentProductId);
        }

        String uploadDir = getText(KEY_PRODUCT_IMAGE_DIR);
        log.debug("file upload dir:" + uploadDir);
        if(image != null) {

            String toPath = uploadDir + "/" + currentProductId + "/" + imageFileName;
            File toFile = new File(toPath);
            toFile.getParentFile().mkdirs();
            image.renameTo(toFile);
        }
        return SUCCESS;
    }
    // ----------------------------------
    // for image upload end
    // ----------------------------------

    //-------------------------------------------------
    // action end
    //-------------------------------------------------
	
    public List<Catalog> getCatalogPath() {
        return catalogPath;
    }

    public List<Catalog> getSubCatalog() {
        return subCatalog;
    }



    public int getCurrentCatalogId() {
        return currentCatalogId;
    }

    public void setCurrentCatalogId(int currentCatalogId) {
        this.currentCatalogId = currentCatalogId;
    }

    public List<Product> getProductList() {
        return productList;
    }



    /*
    @Action( 
        value="/management/productCatalogChoose",
        results={
            @Result(name="success", location="/WEB-INF/content/management/product.jsp")
        }
    )
    public String catalogChoose() {
        product.setId(111);
        product.setCatalogId(123);
        product.setName("Product A");
        product.setDescription("This is a product");
        product.setPrice("123");
        return SUCCESS;
    }
    */
    // ---- get set method ----

    // ---- model driven method ----
    public Product getModel() {
        return product;
    }
}
